<template>
  <div class="container">
    <el-form :model="form">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item class="name">
            <el-input v-model="form.searchValue" placeholder="企业名称/用户名/手机号码/邮箱"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-select v-model="form.staffAuthStatus" placeholder="个人认证状态">
              <el-option label="等待认证" :value="1"></el-option>
              <el-option label="审核通过" :value="2"></el-option>
              <el-option label="审核不通过" :value="3"></el-option>
              <el-option label="未认证" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="创建时间" class="time" label-width="100px">
            <el-date-picker v-model="createTime" type="daterange" range-separator="-" start-placeholder="开始时间"
              end-placeholder="结束时间" :default-value="today" value-format='yyyy-MM-dd HH:mm:ss'>
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item class="btn_box">
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="primary" @click="reset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="authBox">
      <el-button type="info" @click="allStaffAuth">员工认证</el-button>
      <el-button type="info" @click="delAccount">删除</el-button>
    </div>
    <el-table :data="tableData" tooltip-effect="dark" style="width: 100%" align="center"
      @selection-change="handleSelectionChange" :fit='true'>
      <el-table-column type="selection" width="55"></el-table-column>
      <!-- <el-table-column prop="userName" label="用户名" show-overflow-tooltip></el-table-column> -->
      <el-table-column prop="phone" label="手机号码" show-overflow-tooltip></el-table-column>
      <el-table-column prop="mail" label="邮箱" show-overflow-tooltip></el-table-column>
      <el-table-column prop="companyName" label="所属公司" show-overflow-tooltip></el-table-column>
      <el-table-column label="员工认证状态" width="120">
        <template slot-scope="scope">
          <span class="auth_span">{{scope.row.staffAuthStatus | getName}}</span>
          <el-button type="text" @click="singleExamine('2',scope.row)">{{scope.row.staffAuthStatus!==2?'审核':'查看'}}
          </el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="staffAuthStatus" label="员工认证状态" show-overflow-tooltip></el-table-column> -->
      <el-table-column prop="registerTime" label="创建时间" show-overflow-tooltip></el-table-column>
      <el-table-column prop="lastLoginTime" label="最近登录时间" show-overflow-tooltip></el-table-column>
      <el-table-column prop="userLoginCount" label="登录次数" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="manage(scope.row)">管理</el-button>
          <el-button type="text" size="small" @click="changeVisible(scope.row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="form.page" :page-sizes="[10, 20, 30, 40]" :page-size="form.size"
        layout="prev, pager, next, jumper, sizes, total" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="重置密码" :visible.sync="passwordVisible" width="500px" class="resetPassword"
      :before-close="handleClose">
      <el-form ref="passwordForm" :model='passwordForm' :rules='rules'>
        <el-form-item prop="password">
          <el-input placeholder="密码" v-model="passwordForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input placeholder="确认密码" v-model="passwordForm.repassword" show-password></el-input>
        </el-form-item>
        <el-form-item class="mid_box">
          <el-button type="primary" @click="resetPassword">确 定</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="批量审核" :visible.sync="dialogVisible" width="30%" class="examine" :before-close="examineClose">
      <el-form :model="examine" ref="examine" :rules="rules" label-width="100px">
        <el-form-item label="审核结果：" prop="auditStatus">
          <el-radio-group v-model="examine.auditStatus">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="3">不通过</el-radio>
            <el-radio :label="1">待定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核不通过原因：" v-if="examine.auditStatus===3" prop="auditCause">
          <el-input type="textarea" v-model="examine.auditCause" rows='4'></el-input>
        </el-form-item>
        <el-form-item class="mid_box">
          <el-button @click="examineClose">取 消</el-button>
          <el-button type="primary" @click="staffAuth">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { accountList, deleteAccount, resetPassword, batchStaffAuth } from '../../../../api/companyAccount'
import { getEpToken } from '../../../../api/enterprise'
import { encrypt } from '../../../../utils/unitFile'
export default {
  name: 'accountList',
  data () {
    var validateComfirmPwd = (rule, value, callback) => {
      console.log(this.passwordForm.password, value);
      if (this.passwordForm.password != value) {
        callback(new Error('确认密码与密码不一致！'));
      } else {
        callback();
      }
    };
    return {
      createTime: [],
      today: null,
      tableData: [],
      form: {
        page: 1,
        size: 10,
        startTime: '',
        endTime: '',
        staffAuthStatus: '',
        searchValue: ''
      },
      examine: {
        auditCause: '',
        auditStatus: ''
      },
      dialogVisible: false,
      passwordVisible: false,
      passwordForm: {
        companyUserId: '',
        password: '',
        repassword: ''
      },
      total: 0,
      createTime: [],
      choice: [],
      rules: {
        auditStatus: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
        auditCause: [
          { max: 100, message: '原因不能超过100个字' },
          { required: true, message: '请填写审核不通过原因', trigger: 'change' }
        ],
        repassword: [{ required: true, message: '请输入确认密码', trigger: 'change' }, { validator: validateComfirmPwd }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^[0-9a-zA-Z_]{6,20}$/, message: '密码由长度为6-20的数字、字母或下划线组成' }
        ]
      }
    }
  },
  created () {
    this.url = process.env.VUE_APP_URL || '';
    this.today = new Date() - 30 * 24 * 60 * 60 * 1000;
    if (this.$route.query.staffAuthStatus) {
      this.form.staffAuthStatus = Number(this.$route.query.staffAuthStatus)

    }
    this.getList();
  },
  filters: {
    getName (val) {
      switch (val) {
        case 1:
          return '等待认证';
        case 2:
          return '审核通过';
        case 3:
          return '审核未通过';
        default:
          return '未认证';
      }
    }
  },
  watch: {
    // 解析创建时间
    createTime: function (val) {
      this.form.startTime = val[0];
      this.form.endTime = val[1];
    },
    '$route.fullPath': function (val, oldVal) {
      this.$nextTick(() => {

        if (this.$route.query.staffAuthStatus) {
          this.form.staffAuthStatus = Number(this.$route.query.staffAuthStatus)
          this.getList();
        }
      })
    }
  },
  methods: {
    // 重置
    reset () {
      this.createTime = [];
      this.form = {
        page: 1,
        size: 10,
        startTime: '',
        endTime: '',
        staffAuthStatus: '',
        searchValue: ''
      };
      this.getList();
    },
    // 搜索
    search () {
      this.form.page = 1;
      this.form.size = 10;
      this.getList()
    },
    // 获取列表
    getList () {
      accountList(this.form).then(res => {
        if (res.success) {
          this.tableData = res.data.records || [];
          this.total = res.data.total;
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
    },
    // 批量审核
    allStaffAuth () {
      if (this.choice.length < 1) {
        this.$message.error('请选择需要认证的账号!');
      } else {
        this.dialogVisible = true;
      }
    },
    // 删除账号
    delAccount () {
      if (this.choice.length < 1) {
        this.$message.error('请选择想要删除的账号!');
      } else {
        this.$confirm('您要删除账号，删除后不可恢复，是否确定操作？', '信息提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback: action => {
            console.log(action);
            if (action === 'confirm') {
              deleteAccount(this.choice.map(item => item.id)).then(data => {
                console.log(data);
                if (data.success) {
                  this.$message.success('删除成功')
                  this.getList();
                } else {
                  this.$message.error(`${data.msg}`);
                }
              });
            }
          }
        });
      }
    },
    // 跳转企业中心
    manage (row) {
      getEpToken(row.id).then(res => {
        if (res.success) {
          localStorage.setItem('ep_Authorization', res.data.token)
          localStorage.setItem('ep_userName', res.data.userName)
          localStorage.setItem('ep_userId', res.data.userId)
          // window.location.href = 'https://www.baidu.com'
          // window.open('https://www.baidu.com', '_blank');
          window.open(this.url + '/company', '_blank');
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
    },
    changeVisible (row) {
      this.passwordVisible = true;
      this.passwordForm.companyUserId = row.id;
    },
    // 重置密码
    resetPassword () {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          let password = encrypt(this.passwordForm.password);
          let repassword = encrypt(this.passwordForm.repassword)
          let query = {
            id: this.passwordForm.companyUserId,
            password,
            repassword
          }
          // new FormData;
          // query.append('companyUserId', this.passwordForm.companyUserId)
          // query.append('password', password)
          // query.append('repassword', repassword)
          resetPassword(query).then(data => {
            if (data.success) {
              this.$message.success('重置密码成功');
              this.handleClose()
            } else {
              this.$message.error(`${data.msg}`);
            }
          })
        }
      });
    },
    // 提交审核
    staffAuth () {
      this.$refs.examine.validate(valid => {
        if (valid) {
          let query = new FormData();
          query.append('companyUserIds', this.choice.map(item => item.id).join(','))
          query.append('auditStatus', this.examine.auditStatus)
          query.append('auditCause', this.examine.auditCause)
          batchStaffAuth(query).then(data => {
            console.log(data);
            if (data.success) {
              this.$message.success(`审批完成`);
              this.getList();
            } else {
              this.$message.error(`${data.msg}`);
            }
            this.$refs.examine.resetFields();
            this.dialogVisible = false;
          });
        }
      });
    },
    handleClose () {
      this.$refs.passwordForm.resetFields();
      this.passwordVisible = false;
    },
    handleSelectionChange (choice) {
      this.choice = choice;
    },
    handleCurrentChange (val) {
      this.form.page = val;
      this.getList()
    },
    handleSizeChange (val) {
      this.form.size = val;
      this.getList()
    },
    examineClose () {
      this.$refs.examine.resetFields();
      this.dialogVisible = false;
    },
    // 跳转单个审核界面
    singleExamine (index, row) {
      let href = this.$router.resolve({ path: '/authInfo', query: { index, id: row.id, companyId: row.companyId } });
      window.open(href.href, '_blank');
    }
  }
}
</script>

<style lang="css" scoped>
.btn_box {
    text-align: right;
}
.btn_box .el-button {
    width: 100px;
}
.authBox .el-button {
    width: 100px;
    margin-bottom: 20px;
}
.page {
    text-align: center;
    margin-top: 20px;
}
.el-dialog .el-button {
    width: 100px;
}
.mid_box {
    text-align: center;
}
.el-table /deep/ td,
.el-table /deep/ th {
    text-align: center;
}
</style>